package com.lyy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyy.entity.Banner;
import com.lyy.mapper.BannerMapper;
import com.lyy.service.BannerService;
import com.lyy.MinioUtil;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author Liangyaoyun
 */
@Data
public class BannerServiceImpl implements BannerService {
    private BannerMapper bannerMapper;
    @Override
    public int insertByBannerId(Banner banner) {
        return bannerMapper.insertByBannerId(banner);
    }

    @Override
    public int updateByBannerId(Banner banner) {
        return bannerMapper.updateByBannerId(banner);
    }

    @Override
    public int deleteByBannerId(Integer bannerId) {
        return bannerMapper.deleteByBannerId(bannerId);
    }

    @Override
    public int deleteByBannerIds(List<Integer> bannerId) {
        return bannerMapper.deleteByBannerIds(bannerId);
    }


    @Override
    public Banner selectByBannerId(Integer bannerId) {
        return bannerMapper.selectByBannerId(bannerId);
    }

    @Override
    public List<Banner> selectAllBanner() {
        return bannerMapper.selectAllBanner();
    }

    @Override
    public PageInfo<Banner> selectBypage(Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber,pageSize);
        return new PageInfo<>(bannerMapper.selectAllBanner());
    }
    @Override
    public int uploadBanner(MultipartFile bannerFile, Integer bannerId) {
        // 查询旧图片
        Banner banner = bannerMapper.selectByBannerId(bannerId);
        if (null == banner) {
            throw new RuntimeException("轮播图不存在");
        }
        String bannerUrl = banner.getBannerUrl();
        // 从MINIO中删除旧图片: 默认图片不删除
        if (!"default-banner.jpg".equals(bannerUrl)) {
            MinioUtil.delete(bannerUrl, "banner");
        }
        // 向MINIO中上传新图片
        String bannerFileName = MinioUtil.upload(bannerFile, "banner");
        Banner bannerPo = new Banner();
        bannerPo.setBannerId(bannerId);
        bannerPo.setBannerUrl(bannerFileName);
        return bannerMapper.updateByBannerId(bannerPo);
    }

}
